import axios from "axios";
import { getToken,removeUserInfo } from "./user";
import { ElMessage } from "element-plus";
import router from "@/router";
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
axios.defaults.timeout = 8000;

// 添加拦截器
axios.interceptors.request.use((config: any) => {
  // 请求头中添加token 做登录接口校验
  if (getToken()) {
    config.headers.token = getToken()
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

axios.interceptors.response.use((res: any) => {
  // 判断code  401 token过期 403 未登录
  switch (res.data.code) {
    case 401:
      ElMessage({
        message: '登录过期，请重新登录',
        type: 'error'
      })
      removeUserInfo();
      router.replace('/login')
      break;
    case 403:
      ElMessage({
        message: '未登录，请登录访问',
        type: 'error'
      })
      router.replace('/login')
      break;

  }
  return res.data
}, (error) => {
  return Promise.reject(error)
})

export default axios;